package com.wechat.utils.kit;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/1/12.
 */
public class ImageKit {

    public static boolean isImage(String ext){
        if ("jpg".equalsIgnoreCase(ext)
                || "jpeg".equalsIgnoreCase(ext)
                || "png".equalsIgnoreCase(ext)
                || "gif".equalsIgnoreCase(ext)
                || "bmp".equalsIgnoreCase(ext)){
            return true;
        }
        return false;
    }

    /**
     * 获取inputFilePath的后缀名，如："e:/test.pptx"的后缀名为："pptx"<br>
     *
     * @param inputFilePath
     * @return
     */
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    /**
     * 将base64格式的图片解析成图片格式
     * @param files
     * @return
     */
    public static byte[] base64Image(String files){
        BASE64Decoder base64Decoder =new BASE64Decoder();
        byte[] bytes=null;
        try {
            bytes =base64Decoder.decodeBuffer(files);
            for (int j=0;j<bytes.length;j++){
                if (bytes[j]<0){
                    bytes[j]+=256;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return  bytes;
    }

    /**
     * 上传视频
     * @param file 上传的文件
     * @param target /upload/temp/vedio/12547855522.mp3;
     * @throws IOException
     */
    public static void uploadVedio(MultipartFile file,String target) throws IOException {
        File saveFile=new File(target);
        file.transferTo(saveFile);
    }


    public static String video(MultipartFile file, String savePath, HttpServletRequest request){
        String vedio="";
        String path=PathKit.getWebRootPath();
        String newName=null;

        String fileName=file.getOriginalFilename();
        String ext=fileName.substring(fileName.lastIndexOf("."));
        try {
            file.transferTo(new File(path,fileName)); //将文件上传到指定路径
            newName=System.currentTimeMillis()+ext;
            FileKit.renameFile(path,fileName,newName);//对上传的文件进行重命名
            vedio+=savePath+"/"+newName;
        }catch (Exception e){
            e.printStackTrace();
        }
        return vedio;

    }

    /**
     * 检验图片是否合法
     * @param images
     * @return
     */
    public static Boolean imageLegal(String images){
        Image image=null;
        File imageFile=new File(images);
        if (!imageFile.exists()) {
            System.out.println("不存在");
            return false;
        }
        try {
            image = ImageIO.read(imageFile);
            if (image == null || image.getWidth(null) <= 0 || image.getHeight(null) <= 0) {
                return false;
            }else {
                System.out.println("合法");
                return true;
            }
        }catch (Exception e){
            return false;
        }
    }


    public static String base64ToImage(String base64Str,String savePath){
        String imageName=null;
        if (base64Str==null)return null;
        String file=null;
        byte [] bytes= ImageKit.base64Image(base64Str);
        OutputStream outputStream =null;
        try {
            imageName=IdWokerKit.getId()+".jpg";
            file=savePath+"/"+imageName;

            outputStream = new FileOutputStream(PathKit.getWebRootPath()+file);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){

                try {
                    outputStream.flush();
                    outputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return file;
    }

    /**
     * MrWang
     *
     * 图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
     * @param source 源文件        示例： /var/data/images/123.jpg
     * @param target 压缩后的文件  示例：/var/data/images/new123.jpg
     * @param scale 缩放比例 1：不缩放  >1 放大  <1 缩小
     * @param quality 大小压缩质量    0-1 之间的值
     * @return
     */
    public static void thumbnailsImage(String source,String target,double scale,double quality) throws IOException {

        File fromFile=new File(source);
        File toFile=new File(target);
        Thumbnails.of(fromFile).scale(scale).outputQuality(quality).toFile(toFile);



    }

    public static void scaleImage(File fromFile, File toFile, double scale, double quality) throws IOException{
        Thumbnails.of(fromFile).scale(scale).outputQuality(quality).toFile(toFile);
    }

    /**
     * MrWang
     * 设置图片为指定的宽高
     * @param formFile 原图片                      示例： /var/data/images/123.jpg
     * @param toFile 压缩后的图片                   示例：/var/data/images/new123.jpg
     * @param width 压缩的宽度
     * @param height 压缩的高度
     * @param keepAspectRatio 是否保持等比压缩
     * @return
     */
    public static void thumbnailsImage(String formFile,String toFile,int width,int height,boolean keepAspectRatio) throws IOException {

        Thumbnails.of(formFile).size(width, height).keepAspectRatio(keepAspectRatio).toFile(toFile);



    }
    public static void thumbnailsImage(File fromFile,File toFile,int width,int height,boolean keepAspectRatio) throws IOException{
        Thumbnails.of(fromFile).size(width, height).keepAspectRatio(keepAspectRatio).toFile(toFile);
    }
}
